package cn.sdormitory.component.bindValue;

import cn.sdormitory.component.bindValue.annotation.BindValueMethod;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Component
@Aspect
@Slf4j
public class BindValueAspect {

    @Autowired
    private BindValueHelper bindValueHelper;

    /**
     * controller.get切点
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void withGetMappingAnnotation() {
    }

    /**
     * controller.get切点
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)")
    public void withPostMappingAnnotation() {
    }

    /**
     * BindValueMethod切点
     */
    @Pointcut("@annotation(cn.sdormitory.component.bindValue.annotation.BindValueMethod)")
    public void withBindValueMethodAnnotation() {
    }

    /***
     * 环绕增强切入
     * 是controller且有RequestMapping注解
     * @param point 连接点
     */
    @Around(value = "withGetMappingAnnotation() || withPostMappingAnnotation() || withBindValueMethodAnnotation()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object res = point.proceed();
        if(isAspect(point)){
            handleMethodResult(res);
        }
        return res;
    }

    /**
     * 处理方法返回值
     * @param res 方法返回值
     */
    private void handleMethodResult(Object res) {
        bindValueHelper.bindValue(res);
    }

    /**
     * 是否需要增强
     * @param point 链接点
     * @return true增强
     */
    private boolean isAspect(ProceedingJoinPoint point) {
        Method method = getMethod(point);
        BindValueMethod bindValueMethod = method.getAnnotation(BindValueMethod.class);
        return bindValueMethod == null || bindValueMethod.aspect();
    }

    /**
     * 返回连接点方法对象
     * @param point 连接点
     * @return 方法对象
     */
    private static Method getMethod(ProceedingJoinPoint point) {
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        return methodSignature.getMethod();
    }

}

